<?php
namespace app\api\controller;

class Admin extends Permission
{
    public function getList()
    {
        $page = $this->input_data['page'] ? $this->input_data['page'] : 1;
        $limit = $this->input_data['limit'] ? $this->input_data['limit'] : 15;
        $map = array();
        if(isset($this->input_data['status'])) $map['status'] = $this->input_data['status'];
        if(isset($this->input_data['roles']) && $this->input_data['roles'] > 0) $map['roles'] = $this->input_data['roles'];
        $total = db('Admin')->where($map)->count();
        $row = db('Admin')->order('status', 'desc')->page($page,$limit)->where($map)->select();
        $list = [];
        $query = db('AdminRoles')->select();
        $rolesText = [];
        $rolesText[] = '';
        foreach ($query as $v) {
            $rolesText[$v['id']] = $v['title'];
        }
        foreach ($row as $v) {
            $userSites = db('AdminArea')->alias('a')->join('company_area b','a.area_id = b.id','LEFT')->where(['admin_id'=>$v['id']])->order('sort ASC,id DESC')->select();
            $areas = [];
            foreach ($userSites as $s) {
                $s['id'] = $s['area_id'];
                $areas[] = $s;
            }
            $v['area_id'] = $areas;

            $v['rolesText'] = $rolesText[$v['roles']];
            // $v['companys'] = explode(',', $v['companys']);
            // $intIds = [];
            // foreach ($v['companys'] as $c) {
            //     $intIds[] = intval($c) * 1;
            // }
            // $v['companys'] = $intIds;
            $list[] = $v;
        }
        
        $data = array(
            'total' => $total,
            'list' => $list     
        );
        $this->resSuc($data);
    }
    public function info()
    {
        $data = $this->user;
        $data['nickname'] = $this->user['realname'];
        $data['avatar'] = 'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif';
        if($this->user['id'] == 3 || $this->user['id'] == 1)
        {
            # 超管的
            $router = db('AdminRouter')->order('sort ASC,menuId ASC')->select();
            $data['authorities'] = $this->_setDot($router);
        }
        else
        {
            $map = [
                'admin_id' => $this->user['id']
            ];
            $router = db('AdminRules')->alias('a')->join('admin_router b','a.router_id = b.menuId','LEFT')->order('sort ASC,menuId ASC')->field('a.id,b.*')->where($map)->select();
            $data['authorities'] = $this->_setDot($router);
        }

        $data['note'] = '';
        $nMap = [
            'role' => $this->user['roles'],
            'done' => 0
        ];
        if( $note = db('NoticeList')->where($nMap)->find() )
        {
            $data['note'] = $note['title'];
            db('NoticeList')->where(['id'=>$note['id']])->update(['done'=>1]);
        }
        $data['wtf'] = $note;
        $data['map'] = $nMap;
        $data['sql'] = db()->getLastSql();
        

        
        // $router = db('AdminRouter')->order('sort ASC,menuId ASC')->select();
        // $data['authorities'] = $this->_setDot($router);

        $this->resSuc($data);
    }

    // 设置红点
    private function _setDot($router)
    {
        $dotMeta = [
            'props' => [
                'badge' => [
                    'isDot' => true
                ]
            ]
        ];

        $value = [
            'props' => [
                'badge' => [
                    'value' => 3,
                    'type' => 'warning'
                ]
            ]
        ];
        
        // foreach ($router as $k => $v) {
        //     // 保险报价 58
        //     // 待报价
        //     $a = false;
        //     if($v['menuId'] == 58)
        //     {
        //         $InsurancePlan = $this->_getInsurancePlan();
        //         if($InsurancePlan > 0) $a = true;
        //     }
        //     if($a) $router[$k]['meta'] = $dot;
        // }
        $data = $this->_getMissionCount($router);
        $res = $data['res'];
        $dot = $data['dot'];

        foreach ($router as $k => $v) {
            foreach ($dot as $dk => $dv) {
                if( $v['menuId'] == $dk && $dv > 0 ) 
                {
                    $value = [
                        'props' => [
                            'badge' => [
                                'value' => $dv,
                                'type' => 'danger'
                            ]
                        ]
                    ];
                    $router[$k]['meta'] = $value;
                }
            }
            foreach ($res as $r) {
                if($v['menuId'] == $r['id'] && $r['count'] > 0)
                {
                    $value = [
                        'props' => [
                            'badge' => [
                                'value' => $r['count'],
                                'type' => 'warning'
                            ]
                        ]
                    ];
                    $router[$k]['meta'] = $value;
                    // var_dump($router[$k]['meta']['props']['badge']);
                }
            }
        }
        return $router;
    }




    // 
    private function _getMissionCount($router)
    {
        $dot = [
            '58' => 0, // 保险
            '69' => 0, // 财务记录
            '52' => 0, // 内勤
            '100' => 0, // 待审核
            '102' => 0, // 待付款
            '105' => 0 //待收款
        ];
        $res = [];
        foreach ($router as $v) {
            if($v['menuId'] == 59)
            {
                # 报价申请
                $map = [
                    'status' => 0
                ];
                $count = db('InsurancePlan')->where($map)->count();
                if($count > 0)
                {
                    $res[] = [
                        'id' => 59,
                        'count' => $count
                    ];
                    $dot[58] += $count;
                }
            }

            if($v['menuId'] == 59)
            {
                # 出单通知
                $map = [
                    'status' => 10
                ];
                $count = db('Trade')->where($map)->count();
                if($count > 0)
                {
                    $res[] = [
                        'id' => 61,
                        'count' => $count
                    ];
                    $dot[58] += $count;
                }
            }

            if($v['menuId'] == 63)
            {
                # 待上传
                $map = [
                    'status' => 20
                ];
                $count = db('Insurance')->where($map)->count();
                if($count > 0)
                {
                    $res[] = [
                        'id' => 63,
                        'count' => $count
                    ];
                    $dot[58] += $count;
                }
            }
            if($v['menuId'] == 94)
            {
                # 退保 - 待处理（上传保单）
                $map = [
                    'status' => 0
                ];
                $count = db('InsuranceRefund')->where($map)->count();
                if($count > 0)
                {
                    $res[] = [
                        'id' => 94,
                        'count' => $count
                    ];
                    $dot[58] += $count;
                }
            }
            if($v['menuId'] == 72)
            {
                # 财务 - 待付款买保险
                $map = [
                    'status' => 10
                ];
                $count = db('Insurance')->where($map)->count();
                if($count > 0)
                {
                    $res[] = [
                        'id' => 72,
                        'count' => $count
                    ];
                    $dot[102] += $count;
                }
            }
            if($v['menuId'] == 78)
            {
                # 财务 - 待付退保返点
                $map = [
                    'choose' => 1,
                    'refund_amount' => ['>',0],
                    'refund_rebate_time' => 0
                ];
                $count = db('Insurance')->where($map)->count();
                if($count > 0)
                {
                    $res[] = [
                        'id' => 78,
                        'count' => $count
                    ];
                    $dot[102] += $count;
                }
            }
            if($v['menuId'] == 83)
            {
                # 财务 - 待付返还车主的钱
                $map = [
                    'status' => 0
                ];
                $count = db('ReturnMoney')->where($map)->count();
                if($count > 0)
                {
                    $res[] = [
                        'id' => 83,
                        'count' => $count
                    ];
                    $dot[102] += $count;
                }
            }
            if($v['menuId'] == 96)
            {
                # 财务 - 待退保费给车主
                $map = [
                    'a.status' => 20, // 已从保险公司退保完成
                    'refund_to_driver' => 1, // 需要退款给司机
                    'refund_to_driver_time' => 0 // 还没退款的
                ];
                $count = db('InsuranceRefund')->alias('a')->join('insurance b','a.insurance_id = b.id','LEFT')->where($map)->count();
                if($count > 0)
                {
                    $res[] = [
                        'id' => 96,
                        'count' => $count
                    ];
                    $dot[102] += $count;
                }
            }
            if($v['menuId'] == 103)
            {
                # 财务 - 车辆开支，有支出，待财务付款
                $map = [
                    'a.status' => 20, // 已从保险公司退保完成
                    'refund_to_driver' => 1, // 需要退款给司机
                    'refund_to_driver_time' => 0 // 还没退款的
                ];
                $count = db('InsuranceRefund')->alias('a')->join('insurance b','a.insurance_id = b.id','LEFT')->where($map)->count();
                if($count > 0)
                {
                    $res[] = [
                        'id' => 96,
                        'count' => $count
                    ];
                    $dot[102] += $count;
                }
            }

            if($v['menuId'] == 87)
            {
                # 财务 - 待支付的车辆开支
                $map = [
                    'status' => 0,
                    'io_type' => '支出'
                ];
                $count = db('VehicleIncomeExpense')->where($map)->count();
                if($count > 0)
                {
                    $res[] = [
                        'id' => 87,
                        'count' => $count
                    ];
                    $dot[102] += $count;
                }
            }
            if($v['menuId'] == 91)
            {
                # 财务 - 待审还款
                $map = [
                    'status' => 0
                ];
                $count = db('BillRepayRecord')->where($map)->count();
                if($count > 0)
                {
                    $res[] = [
                        'id' => 91,
                        'count' => $count
                    ];
                    $dot[100] += $count;
                }
            }
            if($v['menuId'] == 101)
            {
                # 财务 - 费用明细表 - 待审核
                $map = [
                    'status' => 0
                ];
                $count = db('CompanyIncomeExpense')->where($map)->count();
                if($count > 0)
                {
                    $res[] = [
                        'id' => 101,
                        'count' => $count
                    ];
                    $dot[100] += $count;
                }
            }
            if($v['menuId'] == 104)
            {
                # 财务 - 车辆的收支 - 待审核
                $map = [
                    'status' => 0
                ];
                $count = db('VehicleIncomeExpense')->where($map)->count();
                if($count > 0)
                {
                    $res[] = [
                        'id' => 104,
                        'count' => $count
                    ];
                    $dot[100] += $count;
                }
            }

            
            if($v['menuId'] == 90)
            {
                # 财务 - 转出 - 待核价
                $map = [
                    'status' => 0
                ];
                $outCountJudge = db('VehicleOut')->where($map)->count();

                # 财务 - 转出 - 待审付款
                $map = [
                    'status' => 50
                ];
                $outCountPayJudge = db('VehicleOut')->where($map)->count();
                if($outCountJudge > 0 || $outCountPayJudge > 0)
                {
                    $res[] = [
                        'id' => 90,
                        'count' => $outCountJudge + $outCountPayJudge
                    ];
                    $dot[100] += $outCountJudge + $outCountPayJudge;
                }
            }




            if($v['menuId'] == 97)
            {
                # 内勤 - 转出 - 待付款
                $map = [
                    'status' => 40
                ];
                $count = db('VehicleOut')->where($map)->count();
                if($count > 0)
                {
                    $res[] = [
                        'id' => 97,
                        'count' => $count
                    ];
                    $dot[52] += $count;
                }
            }
            
        }

        

        $data = [
            'res' => $res,
            'dot' => $dot
        ];
        return $data;
    }


    
    public function logout()
    {
        // 退出登录的代码

        $map['token'] = $this->token;
        $data['act_time'] = time();
        db('LogsLogin')->where($map)->update($data);

        $this->resSuc('success');
    }    
    public function editPassword()
    {
        // 退出登录的代码

        $data['id'] = $this->user['id'];
        $data['password'] = passwordAdmin($this->input_data['password']);
        db('Admin')->update($data);

        $this->resSuc('success');
    }
    public function del()
    {

        if( db('Admin')->delete($this->input_data['id']) )
        {
            $data = array(
                'code' => $this->suc_code,
                'data' => 'success',
            );
            $this->res($data);
        }
        else
        {
            $data = array(
                'code' => $this->err_code,
                'data' => '删除失败',
            );
        }
        
    }

    public function update()
    {
        $data['username'] = $this->input_data['username'];
        // $data['code'] = $this->input_data['code'];
        $data['realname'] = $this->input_data['realname'];
        $data['roles'] = $this->input_data['roles'];

        # 处理所属站点
        $sites = json_decode($this->input_data['area_id'],TRUE);
        $roles = true;
        
        if($this->input_data['id'] > 0)
        {
            # 所属站点
            $map = [
                'admin_id' => $this->input_data['id']
            ];
            db('AdminArea')->where($map)->delete();
            foreach ($sites as $v) {
                $s = [
                    'admin_id' => $this->input_data['id'],
                    'area_id' => $v['id']
                ];
                db('AdminArea')->insert($s);
            }

            # 权限
            $map = [
                'id' => $this->input_data['id']
            ];
            $admin = db('Admin')->where($map)->find();
            if($admin['roles'] != $this->input_data['roles'])
            {
                $map = [
                    'admin_id' => $this->input_data['id'],
                    'roles_id' => $admin['roles']
                ];
                db('AdminRules')->where($map)->delete();
                $roles = true;
            }
            else
            {
                $roles = false;
            }
            


            if(isset($this->input_data['password']) && $this->input_data['password'] != '') $data['password'] = passwordAdmin($this->input_data['password']);
            $data['id'] = $id = $this->input_data['id'];
            db('Admin')->update($data);

        }
        else
        {
            $data['password'] = passwordAdmin($this->input_data['password']);
            $data['created_at'] = time();
            $id = db('Admin')->insertGetId($data);
            foreach ($sites as $v) {
                $s = [
                    'admin_id' => $id,
                    'area_id' => $v['id'],
                ];
                db('AdminArea')->insert($s);
            }
        }

        // 处理权限
        if($roles)
        {
            $row = db('AdminRoles')->where(['id'=>$this->input_data['roles']])->value('router');
            $rules = explode(',',$row);

            foreach($rules as $v)
            {
                $data = [
                    'admin_id' => $id,
                    'router_id' => $v,
                    'roles_id' => $this->input_data['roles'],
                ];
                db('AdminRules')->insert($data);
            }
        }

        $this->resSuc('success');
    }
    public function offline()
    {
        $map['id'] = $this->input_data['id'];

        // $data['last_act_time'] = 0;

        db('Admin')->where($map)->setDec('last_act_time',1801);

        $this->resSuc('success');
    }

    //停用 启用
    public function updateState()
    {
        $sText = ['启用','停用'];
        $st = [1,0];
        $user['id'] = $this->input_data['id'];
        $user['status'] = $st[$this->input_data['status']];

        
        db('Admin')->update($user);

        // $this->actLogs('常规',$sText[$this->input_data['status']].$this->input_data['username'].'的管理员账号');

        $data = array(
            'code' => $this->suc_code,
            'data' => 'success',
        );
        $this->res($data);
    }

    // 生成小程序推广码
    public function getSalesCode()
    {
        $imgname = 'https://ycapi.lw81888.com/static/tuiguangtu/' . $this->getMiniQrcode($this->input_data['id']);

        $this->resSuc($imgname);
    }

    private function createTuiGuangTu($openid,$user_id)
    {
        $imgname = $this->getMiniQrcode($openid,$user_id);
        $filename = ROOT_PATH . 'public' . DS . 'static' . DS . 'images' . DS . 'user_tuiguangtu' . DS . $imgname;

        $dst_path = ROOT_PATH . 'public' . DS . 'static' . DS . 'images' . DS .'tuiguangtu.png';//背景图片路径
        $src_path = $filename;//覆盖图
        //创建图片的实例
        $dst = imagecreatefromstring(file_get_contents($dst_path));
        $src = imagecreatefromstring(file_get_contents($src_path));
        //获取覆盖图图片的宽高
        list($src_w, $src_h) = getimagesize($src_path);
        //将覆盖图复制到目标图片上，最后个参数100是设置透明度（100是不透明），这里实现不透明效果
        imagecopymerge($dst, $src, 235, 990, 0, 0, $src_w, $src_h, 100);

        @unlink($filename);  //删除服务器上二维码图片

        $config = \config('qiniu'); //获取配置信息
        $accessKey = $config['accessKey'];
        $secretKey = $config['secretKey'];
        $auth = new Auth($accessKey, $secretKey,86400*7);
        $bucket = $config['bucket'];
        // 生成上传Token
        $token = $auth->uploadToken($bucket);

        header("Content-type: image/png");
        imagepng($dst,$filename);//根据需要生成相应的图片
         
        $filePath = $filename;
        
        $uploadMgr = new UploadManager();
        list($ret, $err) = $uploadMgr->putFile($token, null, $filePath);
        if($err !== null) {
            $this->err = $err;
        } else {
            @unlink($filename);
            imagedestroy($dst);
            imagedestroy($src);
            return 'http://img.lw81888.com/' . $ret['key'];
        }
    }

    //生成小程序二维码
    private function getMiniQrcode($user_id)
    {

        $appid = 'wx82ee966ac67ed2a7';
        $secret = '18767b4f343d5620f05ad786af007534';//AppSecret(小程序密钥)
        $url_access_token = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$appid.'&secret='.$secret;
        $json_access_token = $this->sendCmd($url_access_token,array());
        $arr_access_token = json_decode($json_access_token,true);
        $access_token = $arr_access_token['access_token'];
        if(!empty($access_token)) {

            $url = 'https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token='.$access_token;
            $data['page'] = 'pages/index/index';
            $data['scene'] = 'parent_id='.$user_id;
            $data['width'] = '280';
            $data = json_encode($data);
            $result = $this->sendCmd($url,$data);
            // var_dump($result);die;
            $name = $user_id;
            file_put_contents('./static/tuiguangtu/facai-'.$name.'.jpg',$result);
            //存储二维码路径
            $arr['qrcode'] = 'facai-'.$name.'.jpg';
            $res = db('Admin')->where(['id' => $user_id])->update($arr);
            // $this->resSuc($arr);
            return $arr['qrcode'];
        } else {
            $arr = array('code'=>0,'msg'=>'ACCESS TOKEN为空！');
            $this->resSuc($arr);
        }
            
    }
     /**
     * 发起请求
     * @param  string $url  请求地址
     * @param  string $data 请求数据包
     * @return   string      请求返回数据
     */
    function sendCmd($url,$data)
    {
        $curl = curl_init(); // 启动一个CURL会话
        curl_setopt($curl, CURLOPT_URL, $url); // 要访问的地址
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); // 对认证证书来源的检测
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2); // 从证书中检查SSL加密算法是否存在
        curl_setopt($curl, CURLOPT_HTTPHEADER, array('Expect:')); //解决数据包大不能提交
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); // 使用自动跳转
        curl_setopt($curl, CURLOPT_AUTOREFERER, 1); // 自动设置Referer
        curl_setopt($curl, CURLOPT_POST, 1); // 发送一个常规的Post请求
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data); // Post提交的数据包
        curl_setopt($curl, CURLOPT_TIMEOUT, 30); // 设置超时限制防止死循
        curl_setopt($curl, CURLOPT_HEADER, 0); // 显示返回的Header区域内容
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 获取的信息以文件流的形式返回

        $tmpInfo = curl_exec($curl); // 执行操作
        if (curl_errno($curl)) {
            echo 'Errno'.curl_error($curl);
        }
        curl_close($curl); // 关键CURL会话
        return $tmpInfo; // 返回数据
    }

    //停用 启用
    public function updateStatus()
    {
        $user['id'] = $this->input_data['id'];
        $user['status'] = $this->input_data['status'];
        $user['token'] = '';
        $user['token_mini'] = '';
        
        db('Admin')->update($user);

        $this->resSuc('操作成功');
    }

    public function updateCompany()
    {
        $map = [
            'id' => $this->input_data['id']
        ];
        $ids = json_decode($this->input_data['companys'],true);
        $data = [
            'companys' => implode(',', $ids)
        ];
        db('Admin')->where($map)->update($data);
        $this->resSuc('ok');
    }
    // 修改密码    
    public function password()
    {
        $data['id'] = isset($this->input_data['id']) ? $this->input_data['id'] : $this->user['id'];
        $data['password'] = passwordAdmin($this->input_data['password']);
        db('Admin')->update($data);

        $this->resSuc('修改成功');
    }
}
